# frozen_string_literal: true

# 可在 ~/.setup-env 文件内配置环境变量，所配置的环境变量会合并到系统环境执行的环境变量中

class LoadEnv
  class << self
    def parse_os
      %w[/etc/redhat-release /etc/issue].each do |path|
        next unless File.exist?(path)

        content = File.read(path)
        os = %w[Ubuntu openSUSE CentOS].find { |name| content[name] }
        return os if os
      end

      nil
    end

    def load_default
      {
        'OS' => parse_os
      }
    end

    def load_from_file(path)
      if File.exist?(path)
        lines = File.read(path).split("\n")
        lines = lines.reject { |line| line.start_with?('#') }
        lines = lines.reject { |line| line.strip.empty? }

        lines.map do |line|
          line.split('=', 2)
        end.to_h
      else
        {}
      end
    end

    def merge_env(*envs)
      final_env = {}
      envs.each do |env|
        env = env.reject { |_key, value| value.nil? || value.empty? }
        final_env.merge!(env)
      end
      final_env
    end

    def load_env
      initial_env = load_from_file(File.join(__dir__, '../.setup-env'))
      default_env = load_default
      user_env = load_from_file(File.join(Dir.home, '.setup-env'))

      env = merge_env(initial_env, default_env, user_env)

      env.each do |key, value|
        ENV[key] = value unless ENV.key?(key)
      end
    end
  end
end
